/**
 * 
 */
package com.autoscript.ui.helper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 动态装入jar
 * 作者:龙色波
 * 日期:2013-10-30
 */
public class DriverHelper {
	/**
	  * description:由一个jar文件中取出所有的驱动类
	  *
	  * @param file    *.jar，绝对路径
	  * @return  返回所有驱动类
	  */
	public static Set<String> getDrivers(String file) {
	  JarFile jar = null;
	  Set<String> set = new HashSet<String>();
	  try {
	   jar = new JarFile(file);
	  } catch (IOException e) {
	   return null;
	  }
	  Enumeration<JarEntry> entries = jar.entries();
	 
	  URLClassLoader loader = getLoad(file);
	  String name;
	  while(entries.hasMoreElements()) {
	   JarEntry entry = entries.nextElement();
	   if(entry.getName().endsWith("Driver.class")) {
	    name = entry.getName();
	    name = name.substring(0, name.length() - 6);
	    name = name.replaceAll("/", ".");
	    Class<?> cc = null;
	    try {
	     cc = loader.loadClass(name);
	    } catch (ClassNotFoundException e) {
	     continue;
	    }
	    if(isDriver(cc))
	     set.add(name);
	   }
	  }
	 
	 
	  return set;
	}

	/**
	  * description:判断是否是数据驱动
	  *
	  * @param clazz
	  * @return
	  */
	public static boolean isDriver(Class<?> clazz) {
	  Class<?>[] ccc = clazz.getInterfaces();
	  boolean flag = false;
	  for(Class<?> aa : ccc) {
	   if(aa.getName().equals("java.sql.Driver")) {
	    flag = true;
	   }
	  }
	  if(!flag) {
	   for (; clazz != null; clazz = clazz.getSuperclass()) {
	     Class<?>[] interfaces = clazz.getInterfaces();
	    for(Class<?> aa : interfaces) {
	     if(aa.getName().equals("java.sql.Driver")) {
	      flag = true;
	     }
	    }
	   }
	  }
	  return flag;
	}

	/**
	  * description:根据一个文件(jar)，返回一个ClassLoader
	  *
	  * @param file  *.jar，绝对路径
	  * @return   返回一个ClassLoader
	  */
	public static URLClassLoader getLoad(String file) {
	  URL[] url = null;
	  try {
	   url = new URL[]{new URL("file:"+file)};
	  } catch (MalformedURLException e) {
	   return null;
	  }
	  URLClassLoader loader = new URLClassLoader(url,Thread.currentThread().getContextClassLoader());
	  return loader;
	}

	/**
	  * description:
	  *
	  * @param file  一个jar文件(绝对路径)
	  * @param clazz  需要加载的class路径com.mysql.jdbc.MysqlDriver
	  * @return
	  */
	public static Class<?> getDynamic(String file, String clazz) {
	  URLClassLoader loader = getLoad(file);
	  try {
	   return loader.loadClass(clazz);
	  } catch (ClassNotFoundException e) {
	   e.printStackTrace();
	  }
	  return null;
	}

}
